<template>
  <div class="index">
    <el-row type="flex" class="btn">
      <el-button type="success" @click="createNewAlbumMethod"
        >新建歌单</el-button
      >
      <!-- 新建歌单组件 -->
      <createNewAlubumComponent
        v-if="createNewAlbumFlag"
        @createNewAlbumCpmClose="createNewAlbumCpmClose"
      />
    </el-row>
    <el-row>
      <el-table :data="list" v-if="list.length != 0">
        <el-table-column type="expand">
          <template slot-scope="{ row }">
            <ul class="details">
              <li>
                <div class="name">名称 :</div>
                <GlobalImageDeep
                  :imgWidth="40"
                  :imgHeight="40"
                  :url="row.coverImgUrl"
                  class="img"
                />

                <span @click="toCategoryDetailsPage(row.id)">{{
                  row.name
                }}</span>
              </li>
              <li>
                <div class="name">创建者 :</div>
                <GlobalImageDeep
                  :imgWidth="40"
                  :imgHeight="40"
                  :url="row.creator.avatarUrl"
                  class="img"
                />
                {{ row.creator.nickname }}
              </li>

              <li>
                <div class="name">创建时间 :</div>
                {{ formatCreateTime(row.createTime) }}
              </li>
              <li>
                <div class="name">更新时间 :</div>
                {{ formatUpdateTime(row.updateTime) }}
              </li>
              <li>
                <div class="name">曲目数 :</div>
                {{ getCount(row.trackCount) }} &nbsp;个
              </li>
              <li>
                <div class="name">播放次数 :</div>
                {{ getCount(row.playCount) }} &nbsp;个
              </li>
              <li>
                <div class="name">描述 :</div>
                {{ row.description ? row.description : "用户未设置" }}
              </li>
              <li>
                <div class="name">标签 :</div>
                <div v-if="row.tags.length == 0">用户未设置标签</div>
                <div v-else class="tag">
                  <el-tag
                    type="info"
                    effect="plain"
                    v-for="(item, index) in row.tags"
                    :key="index"
                    >{{ item }}</el-tag
                  >
                </div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column type="index" label="" align="center">
        </el-table-column>
        <el-table-column prop="name" label="名称" align="center">
        </el-table-column>
        <el-table-column prop="name" label="创建时间" align="center">
          <template slot-scope="{ row }">
            {{ formatCreateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="trackCount" label="曲目数" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <el-button
              @click="updateAlbumInfo(row)"
              type="primary"
              icon="el-icon-edit"
              circle
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="delAlbum(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row v-else type="flex" justify="center">
        <img
          src="../../../../assets/images/loading.3708220b.gif"
          alt=""
          height="200"
          width="200"
        />
      </el-row>
    </el-row>

    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      class="eldialogBox"
      @close="closeDialog"
    >
      <el-form
        label-width="80px"
        label-position="left"
        :model="updateForm"
        :rules="updateFormRule"
        ref="updateFormRef"
      >
        <el-form-item label="歌单名称" prop="name">
          <el-input v-model="updateForm.name"></el-input>
        </el-form-item>
        <el-form-item label="歌单标签" prop="tags">
          <el-select
            v-model="selectData"
            multiple
            collapse-tags
            filterable
            placeholder="请选择歌单标签"
            :popper-append-to-body="false"
            @change="seleectChange"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="歌单描述" prop="desc">
          <el-input type="textarea" v-model="updateForm.desc"></el-input>
        </el-form-item>

        <!-- 图片 -->
        <updateImgComponent
          v-if="dialogVisible"
          :info="updateImgComponentInfo"
          @updateUserAlbum="updateUserAlbum"
        />
        <el-row type="flex" justify="center" class="btn">
          <el-button type="success" @click="updateAlbum">更新</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { getCount } from "../../../../utils/format";
import {
  getUserAlbum,
  delAlbum,
  getAllAlbumTags,
  updateAlbum,
} from "../../../../api/myMusicApi";
import { mapState, mapMutations, mapActions } from "vuex";
import updateImgComponent from "./updateImg";
import createNewAlubumComponent from "./createNewAlubum.vue";
export default {
  name: "index",
  components: { updateImgComponent, createNewAlubumComponent },
  data() {
    var checkDesc = (rule, value, callback) => {
      console.log(value);
      if (value.length === 0) {
        callback(new Error("请输入歌单描述"));
      } else {
        callback();
      }
    };
    return {
      list: [],
      dialogVisible: false,
      title: "",
      updateForm: {
        id: "",
        name: "",
        desc: "",
        tags: "",
      },
      selectData: [],
      updateFormRule: {
        name: [{ required: true, message: "请输入歌单名称", trigger: "blur" }],
        desc: [
          {
            required: true,
            message: "请输入歌单描述",
            trigger: "blur",
          },
          {
            validator: checkDesc,
            trigger: "blur",
          },
        ],
        tags: [{ required: true, message: "请选择歌单标签", trigger: "blur" }],
      },
      options: [],
      updateImgComponentInfo: {},
      createNewAlbumFlag: false,
    };
  },
  created() {
    // setTimeout(() => {
    this.getUserAlbumMethod();
    this.getAllAlbumTagsMethod();
    // }, 1500);
  },
  methods: {
    getCount,
    async getUserAlbumMethod() {
      let res = await getUserAlbum(this.userStoreProfile.userId);
      // console.log(res);
      if (res.code === 200) {
        this.playList = res.playlist;
        this.userLikeSongsAlbumId = res.playlist[0].id;
        res.playlist?.forEach((item, index) => {
          if (index !== 0 && item.subscribed === false) {
            this.list.push(item);
          }
        });
      }
    },
    async getAllAlbumTagsMethod() {
      let result = await getAllAlbumTags();
      if (result.code === 200) {
        let arr = [];
        result.sub.forEach((item) => {
          arr.push({ label: item.name, value: item.name });
        });

        // console.log(arr);
        this.options = arr;
      }
    },
    delAlbum(item) {
      "此操作将永久删除该文件, 是否继续?";
      this.$confirm(
        `此操作将永久删除由 ${item.creator.nickname} 创建的 ${item.name} 歌单，是否继续`,
        "提示！！！",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        }
      )
        .then(async () => {
          let result = await delAlbum(item.id);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: `成功删除由 ${item.creator.nickname} 创建的 ${item.name} 歌单`,
            });
            setTimeout(() => {
              this.$message({
                type: "info",
                message: `删除操作有延迟，如若立即查看，请重新登陆！`,
              });
            }, 2000);
            this.list = [];
            this.getUserAlbumMethod();
          }
        })
        .catch(() => {});
    },
    // 打开更新歌单信息的  弹窗框
    updateAlbumInfo(item) {
      this.updateImgComponentInfo = item;

      this.title = "更新" + "  " + item.name + " " + "歌单";
      this.updateForm.id = item.id;
      this.updateForm.desc = item.description ? item.description : "";
      this.updateForm.name = item.name;
      if (item.tags.length != 0) {
        this.selectData = item.tags;
      }
      // this.updateForm.tags = item.tags.length !=0 ?
      // 更新 此歌单的一些信息
      this.dialogVisible = true;
    },
    // 向服务器提交更新 信息
    updateAlbum() {
      this.$refs.updateFormRef.validate(async (flag) => {
        if (flag) {
          let result = await updateAlbum(this.updateForm);
          if (result.code === 200) {
            this.$refs.updateFormRef.resetFields();
            this.list = [];
            this.getUserAlbumMethod();
            this.dialogVisible = false;
            this.updateImgComponentInfo = {};
          }
        }
      });
    },
    closeDialog() {
      console.log("关闭");
      this.updateForm = {
        id: "",
        name: "",
        desc: "",
        tags: "",
      };
      this.title = "";
      this.updateImgComponentInfo = {};
    },
    // 用户 重新上传了歌单的背景图片
    updateUserAlbum() {
      console.log("用户上传了新的图片");
      this.list = [];
      this.getUserAlbumMethod();
    },
    // 用户 点击 新建个单
    createNewAlbumMethod() {
      this.createNewAlbumFlag = true;
    },
    // 创建歌单的组件关闭
    createNewAlbumCpmClose(refreshFlag) {
      if (refreshFlag) {
        this.getUserAlbumMethod();
        this.list = [];
      }
      console.log("关闭");
      this.createNewAlbumFlag = false;
    },

    formatCreateTime(time) {
      return moment(time).format("YYYY-MM-DD");
    },
    formatUpdateTime(time) {
      return moment(time).fromNow();
    },
    // 下拉选择菜单改变的函数
    seleectChange(data) {
      console.log(data);
      this.updateForm.tags = data.join(";");
    },
    toCategoryDetailsPage(id) {
      this.$router.push(`/categoryDetails/${id}`);
    },
  },
  computed: {
    ...mapState({
      userStoreProfile: (state) => state.userStore.profile,
      userStoreCookie: (state) => state.userStore.cookie,
      userStoreToken: (state) => state.userStore.token,
      userStoreUserDetail: (state) => state.userStore.userDetail,
    }),
  },
};
</script>

<style lang="less" scoped>
.index {
  .btn {
    /deep/ .el-button--success {
      background-color: @globalColor;
    }
  }
  .eldialogBox {
    /deep/ .el-select-dropdown__item.selected {
      color: @globalColor;
    }
  }

  // /deep/ .el-table__body tr:hover > td.el-table__cell {
  //   background-color: @globalColor;
  // }
  .details {
    padding: 15px 30px;
    color: #999999;
    li {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      span {
        cursor: pointer;
        &:hover {
          color: @globalColor;
        }
      }
      .name {
        margin-right: 10px;
      }
      .img {
        margin-right: 8px;
        /deep/ .el-image img {
          border-radius: 50%;
        }
      }
      .tag {
        display: flex;

        align-items: center;
        flex-wrap: wrap;
        /deep/ .el-tag {
          height: 22px;
          line-height: 22px;
          margin-right: 5px;
        }
      }
    }
  }
}
</style>
